import React from 'react';
import { Spin, Card, Skeleton } from 'antd';
import dynamic from 'umi/dynamic';
import PropTypes from 'prop-types';

function Loader(props) {
  let result = <Spin />;
  if (props.error) {
    result = <span className="text-warning">未找到指定模块，请检查路径！</span>;
  }
  return (
    <div
      className="text-center"
      style={{ height: 60, background: '#fff', border: '1px solid #e8e8e8' }}
    >
      <div className="middle-item">
        <b className="middle-item-hack" />
        <div className="middle-item-body">{result}</div>
      </div>
    </div>
  );
}

function loadComponent(path, extraProps) {
  // 必须限定到FormDesigner目录，因为import的时候 会把目标目录下的所有文件单独打包成js
  const C = dynamic({
    loader: () => import(`@/pages/FormDesigner/components/AsyncComponent/Assets/${path}`),
    loading: Loader,
  });
  return <C {...extraProps} />;
}

function AsyncComponent({ path, onChange, value, ...rest }) {
  return (
    <>
      {path ? (
        loadComponent(path, { onChange, value, ...rest })
      ) : (
        <Card>
          <Skeleton avatar paragraph={{ rows: 2 }} />
        </Card>
      )}
    </>
  );
}

AsyncComponent.defaultProps = {
  path: '',
};

AsyncComponent.propTypes = {
  path: PropTypes.string,
};

export default AsyncComponent;
